﻿angular.module('app.authenticate').service('authService', ['$http',
	function ($http) {
		'use strict';
		// persisted authentication status
		var authStatus = {
			isAuthenticated: false,
			authenticatedUser: null
		},
		// web requests to authentication controller
		sendAuthRequest = function (query) {
			return $http({
				url: '/api/Authentication/LogIn',
				method: 'POST',
				data: (query === null || query === undefined ? null : JSON.stringify(query)),
				headers: { 'Content-Type': 'application/json' }
			}).success(function (data, status, headers, config) {
				authStatus.isAuthenticated = data.Successful;
				authStatus.authenticatedUser = data.Content;
			}).error(function (data, status, headers, config) {
				authStatus.isAuthenticated = false;
				authStatus.authenticatedUser = null;
			});
		},
		authenticate = function (email, password) {
			return sendAuthRequest({ email: email, password: password });
		},
		logOut = function () {
			return $http({
				url: '/api/Authentication/LogOut',
				method: 'POST',
				data: null,
				headers: { 'Content-Type': 'application/json' }
			}).success(function (data, status, headers, config) {
				authStatus.isAuthenticated = false;
				authStatus.authenticatedUser = null;
			}).error(function (data, status, headers, config) { });
		},
		register = function (nickname, username, password) {
			var query = { nickname: nickname, email: username, password: password };
			return $http({
				url: '/api/Authentication/Register',
				method: 'POST',
				data: JSON.stringify(query),
				headers: { 'Content-Type': 'application/json' }
			}).success(function (data, status, headers, config) {
				authStatus.isAuthenticated = data.Successful;
				authStatus.authenticatedUser = data.Content;
			}).error(function (data, status, headers, config) {
				authStatus.isAuthenticated = false;
				authStatus.authenticatedUser = null;
			});
		},
		resetPassword = function (email) {
			return $http({
				url: '/api/Authentication/ResetPassword',
				method: 'POST',
				data: JSON.stringify({ email: email, password: '' }),
				headers: { 'Content-Type': 'application/json' }
			});
		},
		changePassword = function (oldPassword, newPassword) {
			return $http({
				url: '/api/Authentication/ChangePassword',
				method: 'POST',
				data: JSON.stringify({ oldPassword: oldPassword, newPassword: newPassword }),
				headers: { 'Content-Type': 'application/json' }
			});
		},
		// build service and avilable methods
		svc = {
			authenticate: authenticate,
			authStatus: authStatus,
			logOut: logOut,
			register: register,
			resetPassword: resetPassword,
			sendAuthRequest: sendAuthRequest,
			changePassword: changePassword
		};

		return svc;
	}]);